import React, { useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { useState } from 'react'
type Props = React.DetailedHTMLProps<
  React.TextareaHTMLAttributes<HTMLTextAreaElement>,
  HTMLTextAreaElement
> & {
  value: string
  onChange: (e: string) => void
}
export default function Textarea({
  maxLength = 100,
  value,
  onChange,
  ...rest
}: Props) {
  const inpref = useRef<HTMLTextAreaElement>(null)
  const [content, setValue] = useState('')
  useEffect(() => {
    setValue(value)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  useEffect(() => {
    inpref.current!.focus()
    // setValue(value)
  }, [value])
  const onValueChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setValue(e.target.value)
    onChange?.(e.target.value)
  }
  return (
    <div className={styles.root}>
      <textarea
        className="textarea"
        maxLength={maxLength}
        {...rest}
        ref={inpref}
        value={content}
        onChange={onValueChange}
      />
      <div className="count">
        {(value && value.length) || 0}/{maxLength}
      </div>
    </div>
  )
}
